package news.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import news.entity.News;
import news.entity.Types;
import news.utils.DBUtils;

/**
 * 类型的数据库操作类
 * @author Administrator
 *
 */
public class TypesDAO {
	private NewsDAO newsDAO;
	
	/**
	 * 新增新闻类型到数据库
	 * @param title
	 * @param remark
	 * @return
	 */
	public boolean insertTypes(String title, String remark) {
		boolean flag = false;
		String sql = "insert into newstypeinfo(typesname,remark) values(?,?)";
		Connection conn = DBUtils.getConn();
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1,title);
			pst.setString(2, remark);
			flag = pst.executeUpdate() > 0 ? true : false;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 查询所有的新闻类型
	 * @return
	 */
	public List<Types> queryAllTYpes() {
		List<Types> typesList = null;
		String sql = "select * from newstypeinfo";
		
		Connection conn = DBUtils.getConn();
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			typesList = new ArrayList<>();
			while ( rs.next() ) {
				Types type = new Types();
				type.setTypeid(rs.getInt(1));
				type.setTitle(rs.getString(2));
				type.setRemark(rs.getString(3));
				
				// 查询本类型下的所有的新闻
				List<News> listNews = newsDAO().listNews(type.getTypeid());
				type.setNews(listNews);
				
				typesList.add(type);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return typesList;
	}

	/**
	 * 初始化NewsDAO
	 * @return
	 */
	public NewsDAO newsDAO(){
		if ( newsDAO == null ) {
			newsDAO = new NewsDAO();
		}
		return newsDAO;
	}
}
